package com.softstao.guoyu.ui.activity.agent;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.model.sale.OrderDetail;
import com.softstao.guoyu.model.sale.OrderGoods;
import com.softstao.guoyu.mvp.interactor.agent.AgentInteractor;
import com.softstao.guoyu.mvp.presenter.agent.AgentPresenter;
import com.softstao.guoyu.mvp.viewer.agent.MonthOrderDetailViewer;
import com.softstao.guoyu.ui.adapter.OrderGoodsAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewHolder;
import com.softstao.softstaolibrary.library.activity.ImagePagerActivity;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.FullyGridLayoutManager;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.MarginDecoration;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2018/1/10.
 */

public class AboutOrderDetailActivity extends BaseActivity implements MonthOrderDetailViewer{

    @AIPresenter(presenter = AgentPresenter.class, interactor = AgentInteractor.class)
    AgentPresenter presenter;

    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.order_sn)
    TextView orderSn;
    @BindView(R.id.agent)
    TextView agent;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.total_price)
    TextView totalPrice;
    @BindView(R.id.orderer)
    TextView orderer;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.pay_method)
    TextView payMethod;
    @BindView(R.id.pay_price)
    TextView payPrice;
    @BindView(R.id.pay_memo)
    TextView payMemo;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.img_view)
    RecyclerView imgView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.shipping_view)
    RecyclerView shippingView;
    @BindView(R.id.contact)
    TextView contact;
    @BindView(R.id.contact_orderer)
    TextView contactOrderer;
//    @BindView(R.id.memo)
//    TextView memo;
    @BindView(R.id.cancel_reason)
    TextView cancelReason;
    @BindView(R.id.cancel_view)
    LinearLayout cancelView;

    private String order_code;
    private int agent_id;
    private OrderDetail orderDetail;
    private OrderGoodsAdapter adapter;
    private RecycleViewBaseAdapter<OrderDetail.LogisticsInfoBean> shippingAdapter;
    private RecycleViewBaseAdapter<String> imgAdapter;
    private List<OrderGoods> goodsList = new ArrayList<>();
    private List<String> imgList = new ArrayList<>();
    private List<OrderDetail.LogisticsInfoBean> shippingList = new ArrayList<>();
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int _ContentView() {
        return R.layout.activity_order_detail;
    }

    @Override
    public void initView() {
        initTitle("业绩订单详情");
        bottom.setVisibility(View.GONE);
        order_code = getIntent().getStringExtra("order_code");
        agent_id = getIntent().getIntExtra("agent_id", 0);

        adapter = new OrderGoodsAdapter(goodsList);
        listView.setAdapter(adapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));

        imgAdapter = new RecycleViewBaseAdapter<String>(imgList, R.layout.layout_img) {
            @Override
            public void convert(RecycleViewHolder holder, String s) {
                Glide.with(context).load(s).into((ImageView) holder.getView(R.id.img));
                holder.getView(R.id.img).setOnClickListener(v -> imageBrower(holder.getAdapterPosition(), (ArrayList<String>) imgList));
            }
        };
        imgView.setAdapter(imgAdapter);
        imgView.setLayoutManager(new FullyGridLayoutManager(context, 3));
        imgView.addItemDecoration(new MarginDecoration(this));

        shippingAdapter = new RecycleViewBaseAdapter<OrderDetail.LogisticsInfoBean>(shippingList, R.layout.layout_shipping_item) {
            @Override
            public void convert(RecycleViewHolder holder, OrderDetail.LogisticsInfoBean logisticsInfoBean) {
                RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                holder.itemView.setLayoutParams(layoutParams);
                String company = logisticsInfoBean.getMode() == null ? "—" : logisticsInfoBean.getMode();
                String num = logisticsInfoBean.getLogisticsCode() == null ? "—" : logisticsInfoBean.getLogisticsCode();
                holder.setText(R.id.shipping_company, "快递公司：" + company)
                        .setText(R.id.shipping_num, "物流单号：" + num);
                holder.getView(R.id.copy).setOnClickListener(v -> {
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(num);
                    LZToast.getInstance(context).showToast("复制成功");
                });
            }
        };
        shippingView.setAdapter(shippingAdapter);
        shippingView.setLayoutManager(new FullyLinearLayoutManager(this));

    }

    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    private void initData() {
        status.setText(orderDetail.getStateStr());
        orderSn.setText("订单编号：" + orderDetail.getOrderCode());
        agent.setText("商家：" + orderDetail.getAgentName());
        time.setText("时间：" + format.format(new Date(orderDetail.getOrderDate())));
        totalPrice.setText(getResources().getString(R.string.rmb) + LZUtils.priceFormat(orderDetail.getTotal()));
//        String buy_memo = orderDetail.getRemark() != null ? orderDetail.getRemark() : "—";
//        memo.setText(buy_memo);
        if (TextUtils.isEmpty(orderDetail.getCancelReason()) == false) {
            cancelView.setVisibility(View.VISIBLE);
            cancelReason.setText(orderDetail.getCancelReason());
        } else {
            cancelView.setVisibility(View.GONE);
        }
        if (orderDetail.getConsigneeInfo() != null) {
            orderer.setText("收货人：" + orderDetail.getConsigneeInfo().getName());
            address.setText(orderDetail.getConsigneeInfo().getAddress());
        }
        if (orderDetail.getLogisticsInfo() != null && orderDetail.getLogisticsInfo().size() != 0) {
            shippingList.clear();
            shippingList.addAll(orderDetail.getLogisticsInfo());
            shippingAdapter.notifyDataSetChanged();
        }
        if (orderDetail.getPayInfo() != null) {
            String method = orderDetail.getPayInfo().getWay() != null ? orderDetail.getPayInfo().getWay() : "—";
            String amount = orderDetail.getPayInfo().getPayAmount() != 0 ? LZUtils.priceFormat(orderDetail.getPayInfo().getPayAmount()) : "—";
            String memo = orderDetail.getPayInfo().getPayRemark() != null ? orderDetail.getPayInfo().getPayRemark() : "—";
            payMethod.setText("付款方式：" + method);
            payPrice.setText("付款金额：" + amount);
            payMemo.setText(memo);
            if (orderDetail.getPayInfo().getPayImg() != null && orderDetail.getPayInfo().getPayImg().size() != 0) {
                imgView.setVisibility(View.VISIBLE);
                imgList.clear();
                imgList.addAll(orderDetail.getPayInfo().getPayImg());
                imgAdapter.notifyDataSetChanged();
            } else {
                imgView.setVisibility(View.GONE);
            }
        }
    }

    @OnClick({R.id.contact, R.id.contact_orderer, R.id.copy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.contact:
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + orderDetail.getAgentMobile());
                intent.setData(data);
                startActivity(intent);
                break;
            case R.id.contact_orderer:
                Intent orderIntent = new Intent(Intent.ACTION_DIAL);
                Uri data1 = Uri.parse("tel:" + orderDetail.getConsigneeInfo().getMobile());
                orderIntent.setData(data1);
                startActivity(orderIntent);
                break;
            case R.id.copy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(orderDetail.getOrderCode());
                LZToast.getInstance(context).showToast("复制成功");
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        findMonthOrderDetail();
    }

    @Override
    public void findMonthOrderDetail() {
        loading.setVisibility(View.VISIBLE);
        presenter.getMonthOrderDetail(agent_id, order_code);
    }

    @Override
    public void getMonthOrderDetail(OrderDetail orderDetail) {
        loading.setVisibility(View.GONE);
        if (orderDetail == null) {
            LZToast.getInstance(this).showToast("订单不存在！");
            finish();
        } else {
            this.orderDetail = orderDetail;
            goodsList.clear();
            goodsList.addAll(orderDetail.getOrderProductList());
            adapter.notifyDataSetChanged();
            adapter.setStatus(orderDetail.getState());
            initData();
        }
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }
}
